﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Forums.ForumsClient.Models;

namespace Microsoft.Forums.ForumsClient.Views
{
    /// <summary>
    /// Interaction logic for ForumFolderView.xaml
    /// </summary>
    public partial class ForumFolderView : UserControl
    {
        public ForumFolderView()
        {
            InitializeComponent();
        }

        /// <summary>
        /// Handles the MouseRightButtonDown event of the TreeViewItem control.
        /// When the user right clicks on a treeview item, select that item.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.Input.MouseButtonEventArgs"/> instance containing the event data.</param>
        private void TreeViewItem_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
        {
            var selectableItem = sender as TreeViewItem;
            if (selectableItem != null)
            {
                if (!selectableItem.IsSelected)
                {
                    selectableItem.IsSelected = true;
                }
                e.Handled = true;
            }

        }

        /// <summary>
        /// Since we cannot register to a collection view for subscribed forums we need to updated selected forum
        /// in the view
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void forumTreeView_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            IFolderViewModel selectedValue = null;
            IFolderViewModel selectedValueAlternate = null;
            selectedValue = forumTreeView.SelectedItem as IFolderViewModel;
            if (selectedValue == null)
            {
                var selectedTreeViewItem = forumTreeView.SelectedItem as TreeViewItem;
                if (selectedTreeViewItem != null)
                {
                    selectedValueAlternate = selectedTreeViewItem.Header as IFolderViewModel;
                }
            }

            AppDataModel.Instance.SelectedFolder = selectedValue ?? selectedValueAlternate;
        }
    }
}
